package com.ibeeking.found.common.resolver;

import com.ibeeking.found.common.config.feign.*;
import com.ibeeking.found.common.constants.HeaderNounConstant;
import com.ibeeking.found.common.annotation.LoginUser;
import com.ibeeking.found.common.entity.CurrentUser;
import com.ibeeking.found.common.entity.UserInfoDTO;
import com.ibeeking.found.common.enums.LoginRoleEnum;
import com.ibeeking.nematos.exception.AuthorizationException;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 封装当前登录用户信息
 *
 * @Author ibeeking
 * @date 2020/10/21
 */
public class LoginResolver implements HandlerMethodArgumentResolver {

    private TenantUserClient tenantUserClient;

    private ShopUserClient shopUserClient;

    private GlobalUserClient globalUserClient;

    private CsUserClient csUserClient;

    private CpUserClient cpUserClient;

    public LoginResolver(TenantUserClient tenantUserClient, ShopUserClient shopUserClient, GlobalUserClient globalUserClient, CsUserClient csUserClient, CpUserClient cpUserClient) {
        this.tenantUserClient = tenantUserClient;
        this.shopUserClient = shopUserClient;
        this.globalUserClient = globalUserClient;
        this.csUserClient = csUserClient;
        this.cpUserClient = cpUserClient;
    }

    /**
     * 入参筛选
     *
     * @param methodParameter 参数集合
     * @return 格式化后的参数
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(LoginUser.class) && methodParameter.getParameterType().equals(CurrentUser.class);
    }

    /**
     * @param methodParameter       入参集合
     * @param modelAndViewContainer model 和 view
     * @param nativeWebRequest      web相关
     * @param webDataBinderFactory  入参解析
     * @return 包装对象
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String userId = request.getHeader(HeaderNounConstant.USER_ID);
        if (StringUtils.isBlank(userId)) {
            throw new AuthorizationException("resolveArgument error userId is empty");
        }

        String loginSystem = request.getHeader(HeaderNounConstant.LOGIN_SYSTEM);
        if (StringUtils.isBlank(loginSystem)) {
            throw new AuthorizationException("resolveArgument error loginSystem is empty");
        }
        String loginRole = request.getHeader(HeaderNounConstant.LOGIN_ROLE);
        if (StringUtils.isBlank(loginRole)) {
            throw new AuthorizationException("resolveArgument error loginRole is empty");
        }
        boolean c = LoginRoleEnum.WX_MA.name().equals(loginRole);

        String userName = request.getHeader(HeaderNounConstant.USER_NAME);
        if (StringUtils.isBlank(userName)) {
            userName = "";
        }
        String tenantId = request.getHeader(HeaderNounConstant.TENANT_ID);
        if (StringUtils.isBlank(tenantId) && c) {
            throw new AuthorizationException("resolveArgument error tenantId is empty");
        }
        String tenantIndustry = request.getHeader(HeaderNounConstant.INDUSTRY);
        String shopId = request.getHeader(HeaderNounConstant.SHOP_ID);
        String openId = request.getHeader(HeaderNounConstant.OPEN_ID);
        String amDemoUser = request.getHeader(HeaderNounConstant.AM_DEMO_USER);
        CurrentUser currentUser;
        if (methodParameter.getParameterAnnotation(LoginUser.class).isFull()) {
            //查询用户，角色信息
            ResponseResult<UserInfoDTO> userInfoResult = null;
            if (LoginRoleEnum.GLOBAL.name().equals(loginSystem)) {
                userInfoResult = globalUserClient.queryLoginUser(Long.valueOf(userId));
            } else if (LoginRoleEnum.TENANT.name().equals(loginSystem)) {
                if (StringUtils.isBlank(tenantId)) {
                    throw new AuthorizationException("请选择租户后操作!");
                }
                userInfoResult = tenantUserClient.queryLoginUser(Long.valueOf(userId));
            } else if (LoginRoleEnum.SHOP.name().equals(loginSystem)) {
                if (StringUtils.isBlank(shopId)) {
                    throw new AuthorizationException("请选择商户后操作!");
                }
                userInfoResult = shopUserClient.queryLoginUser(Long.valueOf(userId));
            } else if (LoginRoleEnum.CUSTOMER_SERVICE.name().equals(loginSystem)) {
                userInfoResult = csUserClient.queryLoginUser(Long.valueOf(userId));
            } else if (LoginRoleEnum.WX_CP.name().equals(loginSystem)) {
                if (StringUtils.isBlank(tenantId)) {
                    throw new AuthorizationException("请选择租户后操作!");
                }
                userInfoResult = cpUserClient.queryLoginUser(Long.valueOf(userId));
            } else if (LoginRoleEnum.WX_MA.name().equals(loginSystem)) {

            }
            if (null == userInfoResult || null == userInfoResult.getData()) {
                throw new AuthorizationException("用户不存在!");
            }
            currentUser = BeanUtil.convertBean(userInfoResult.getData(), CurrentUser.class);
        } else {
            currentUser = new CurrentUser();
            currentUser.setId(Long.valueOf(userId));
            currentUser.setName(userName);
        }
        currentUser.setLoginSystem(loginSystem);
        currentUser.setIndustry(tenantIndustry);
        currentUser.setLoginRole(loginRole);
        if (StringUtils.isNotBlank(tenantId)) {
            currentUser.setTenantId(Integer.valueOf(tenantId));
//            CurrentUser.CurrentTenant currentTenant = currentUser.getCurrentTenant();
//            if (null == currentTenant) {
//                currentTenant = new CurrentUser.CurrentTenant();
//                currentTenant.setTenantId(Integer.valueOf(tenantId));
//            }
//            currentUser.getCurrentTenant().setTenantId(Integer.valueOf(tenantId));
        }
        if (StringUtils.isNotBlank(shopId)) {
            CurrentUser.CurrentShop currentShop = currentUser.getCurrentShop();
            if (null == currentShop) {
                currentShop = new CurrentUser.CurrentShop();
                currentUser.setCurrentShop(currentShop);
            }
            currentUser.getCurrentShop().setShopId(Long.valueOf(shopId));
        }
//        if (StringUtils.isNotBlank(openId)) {
//            CurrentUser.CurrentCp currentCp = currentUser.getCurrentCp();
//            if (null == currentCp) {
//                currentCp = new CurrentUser.CurrentCp();
//                currentUser.setCurrentCp(currentCp);
//            }
//            currentUser.getCurrentCp().setAppId(openId);
//        }
        return currentUser;
    }
}
